<?php

namespace Application\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;

class InvitationTable
{
    protected $table ='Invitation';
    protected $tableName ='Invitation';
    
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
    	$this->tableGateway = $tableGateway;
    }
    
    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select(function(Select $select){
            $select->order('idInvit ASC');
        });
        
        return $resultSet;
    }

    public function fetchAllArray()
    {
        $resultSet = $this->fetchAll();
        $entities = array();
        
        foreach ($resultSet as $row) {
        	$obj = new Invitation();
        	$obj->exchangeArray( (array) $row);
        	$entities[] = $obj;
        }
        
        return $entities;
    }

    public function toArray ($resultSet)
    {
        $entities = array();
        
        foreach ($resultSet as $row) {
            $obj = new Invitation();
            $obj->exchangeArray( (array) $row);
            $entities[] = $obj;
        }
        
        return $entities;
    }

    public function isMailInvitationDejaEnBase( Invitation $invitation )
    {
        $mailInvit = $invitation->mailInvit;

        if( $mailInvit == null || $mailInvit == "" ) {
            return false;
        }

        $rowset = $this->tableGateway->select(array('mailInvit' => $mailInvit ));
        $row = $rowset->current();
        if (!$row) {
            return false;
        }
        return true;
    }

    public function saveInvitation(Invitation $invitation)
    {
        $data = (array) $invitation;
        
        $id = (int)$invitation->idInvit;
        
        if ($id == 0) {
            $this->tableGateway->insert($data);
            
            $id = $this->tableGateway->lastInsertValue;
            
        }
        
        return $id;
    }
}